// ============================================================ //
// ============================================================ //
//
// @Group       : QiXin Supply Chain Team
// @Author      : ZhiQiang Cheng
// @Date        : 2024-07-11
// @Description : 获取最后5条投票信息: 每次用户参与投票, 推送一个信号.
//
// ============================================================ //
// ============================================================ //

package job

import (
	"sync/atomic"
	"time"
	"wooha-cache-hub/cache"
	"wooha-cache-hub/dao"

	"github.com/StarfishProgram/starfish-go-sdk/sdklog"
	"github.com/StarfishProgram/starfish-go-sdk/sdktypes"
)

type roomVote struct{}

var RoomVote = new(roomVote)

func (rv *roomVote) Listen(running *atomic.Bool) {
	for running.Load() {
		groupBuyingId, err := cache.PopRoomVoteChannel()
		if err != nil {
			sdklog.Error(err)
			time.Sleep(time.Second)
			continue
		} else if groupBuyingId == nil {
			time.Sleep(time.Second)
			continue
		}

		sdklog.Info("房间投票频道:", groupBuyingId)
		rv.handle(*groupBuyingId)
	}
}

func (rv *roomVote) handle(groupBuyingId sdktypes.ID) {
	list, err := dao.GroupBuyingRoom.GetVoteLast(groupBuyingId)
	if err != nil {
		sdklog.Error(err)
		return
	}

	if err := cache.FlushRoomVote(groupBuyingId, list); err != nil {
		sdklog.Error(err)
		return
	}

	sdklog.Info("房间投票已刷新:", groupBuyingId)
}
